package com.firechatwebclient.websocket;

import com.firechatwebclient.entity.RecivePackge;
import com.firechatwebclient.websocket.WebSocketListener;
import com.firechatwebclient.websocket.util.PackageBuilder;
import org.json.simple.JSONObject;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CountDownLatch;

public class ClientSession extends Thread {
    private static final String serverURI = "ws://thabe.club:23333/";
    private static WebSocket webSocket;

    private static void initializeWebSocket() {
        Thread thread = new Thread(() -> {
            HttpClient client = HttpClient.newHttpClient();
            CountDownLatch latch = new CountDownLatch(1);

            webSocket = client.newWebSocketBuilder()
                    .buildAsync(URI.create(serverURI), new WebSocketListener(latch)).join();

            try {
                latch.await(); // 等待 WebSocket 连接完成
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
    }

    private ClientSession() {
        initializeWebSocket();
    }

    public static ClientSession getInstance() {
        return new ClientSession();
    }

    public WebSocket getWebSocket() {
        return webSocket;
    }

    public void sendPackge(String pack) {
        webSocket.sendText("niubi",false);
        webSocket.sendText(pack, false);
        System.out.println(pack);
    }

    public void recive(JSONObject jsonObject) {
        RecivePackge recivePackge = PackageBuilder.Unpack(jsonObject);
        System.out.println(recivePackge.toString());
    }
}
